package br.com.persistence.daoimpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.persistence.ConnectionManager;
import br.com.persistence.dao.GenericDAO;

public abstract class GenericDAOImpl<T> implements GenericDAO<T> {

	protected EntityManager enManager;
	private Class<T> classe;
	
	public GenericDAOImpl(Class<T> classe) {
		enManager = ConnectionManager.getEntityManager();
		this.classe = classe;
		
	}

	@Override
	public void save(T entity) {
		enManager.persist(entity);

	}

	@Override
	public void update(T entity) {
		enManager.merge(entity);

	}

	@Override
	public void delete(T entity) {
		enManager.remove(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		String sql = "select entity from "+classe.getName()+" entity";
		Query query = enManager.createQuery(sql);
		return query.getResultList();
	}

	@Override
	public T findById(Integer id) {
		return enManager.find(classe, id);
	}

}
